package com.hait.mypicture.controller;

import com.hait.mypicture.annotation.AuthCheck;
import com.hait.mypicture.common.BaseResponse;
import com.hait.mypicture.common.ResultUtils;
import com.hait.mypicture.constant.UserConstant;
import com.hait.mypicture.exception.BusinessException;
import com.hait.mypicture.exception.ErrorCode;
import com.hait.mypicture.manager.CosManager;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Autowired
    private CosManager cosManager;

    /**
     * 文件上传
     * @param multipartFile  文件
     * @return 文件url
     */
    @PostMapping("/upload")
    public BaseResponse<String> upload(@RequestPart("file") MultipartFile multipartFile) {
        //获得上传文件的名称
        String filename = multipartFile.getOriginalFilename();
        //指定文件目录
        String filepath = String.format("/test/%s", filename);
        File file = null;
        try {
            //创建临时文件，此时临时文件中为空
            file = File.createTempFile(filepath, null);

            //将上传的文件写入临时文件中
            multipartFile.transferTo(file);

            //上传文件
            cosManager.putObject(filepath,file);

            //返回文件的url
            return ResultUtils.success(filepath);

        } catch (Exception e) {
            log.error("文件上传失败，filepath = {}" ,filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            //删除临时文件
            if (file != null) {
                boolean delete = file.delete();
                if (!delete) {
                    log.error("文件删除失败，filepath = {}" ,filepath);
                }
            }
        }

    }

    /**
     * 文件下载
     * @param filepath 文件路径
     * @param response 响应
     * @throws IOException
     */
    @GetMapping("/download")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public void download(String filepath, HttpServletResponse response) throws IOException {
        COSObjectInputStream cosObjectInput = null;
        try {
            //获取文件
            COSObject cosObject = cosManager.getObject(filepath);
            //获取文件输入流
            cosObjectInput = cosObject.getObjectContent();
            //获取文件字节数组
            byte[] bytes = IOUtils.toByteArray(cosObjectInput);

            //设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filepath);
            //写入响应
            response.getOutputStream().write(bytes);
            //刷新缓冲区
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("文件下载失败，filepath = {}" ,filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
        } finally {
            //关闭输入流
            if(cosObjectInput != null){
                cosObjectInput.close();
            }
        }
    }
}
